//
//  UIImageViewExtension.swift
//  Common
//
//  Created by 我骑着蜗牛走天下 on 2025/9/20.
//

import UIKit

extension UIImageView {
    
    /// 将图片像素坐标转换成 UIImageVIew 内部的坐标
    public func convertRectFromImagePixelsToImageView(_ rect: CGRect) -> CGRect {
        let imageView = self
        guard let image = imageView.image else {
            return .zero
        }
        
        let imageViewSize = imageView.bounds.size
        
        // 图片尺寸（像素）
        let imgSize = image.size
        // UIImageView 尺寸（点）
        let ivSize = imageViewSize
        
        // 计算图片显示区域的大小和偏移，依据 contentMode
        var scaleFactor: CGFloat = 1.0
        var scaledImageSize = CGSize.zero
        var imageOrigin = CGPoint.zero
        
        switch imageView.contentMode {
        case .scaleAspectFit:
            // 计算缩放比例（保持比例）
            let scaleWidth = ivSize.width / imgSize.width
            let scaleHeight = ivSize.height / imgSize.height
            scaleFactor = min(scaleWidth, scaleHeight)
            
            scaledImageSize = CGSize(width: imgSize.width * scaleFactor, height: imgSize.height * scaleFactor)
            
            // 计算图片在 UIImageView 中的偏移（居中）
            imageOrigin = CGPoint(
                x: (ivSize.width - scaledImageSize.width) / 2,
                y: (ivSize.height - scaledImageSize.height) / 2
            )
            
        case .scaleAspectFill:
            // 计算缩放比例（保持比例）
            let scaleWidth = ivSize.width / imgSize.width
            let scaleHeight = ivSize.height / imgSize.height
            scaleFactor = max(scaleWidth, scaleHeight)
            
            scaledImageSize = CGSize(width: imgSize.width * scaleFactor, height: imgSize.height * scaleFactor)
            
            // 计算图片在 UIImageView 中的偏移（居中，可能裁剪）
            imageOrigin = CGPoint(
                x: (ivSize.width - scaledImageSize.width) / 2,
                y: (ivSize.height - scaledImageSize.height) / 2
            )
            
        case .scaleToFill:
            // 不保持比例，宽高分别缩放
            let scaleX = ivSize.width / imgSize.width
            let scaleY = ivSize.height / imgSize.height
            
            // 直接缩放 rect
            let x = rect.origin.x * scaleX
            let y = rect.origin.y * scaleY
            let width = rect.size.width * scaleX
            let height = rect.size.height * scaleY
            
            return CGRect(x: x, y: y, width: width, height: height)
            
        default:
            // 其他情况，假设图片拉伸填满
            return rect
        }
        
        // 按比例缩放 rect
        let x = rect.origin.x * scaleFactor + imageOrigin.x
        let y = rect.origin.y * scaleFactor + imageOrigin.y
        let width = rect.size.width * scaleFactor
        let height = rect.size.height * scaleFactor
        
        return CGRect(x: x, y: y, width: width, height: height)
    }

}
